package com.tandashi.springbootstudy01.study.thread;

/**
 * 代码思路，
 * 1）需要2把锁
 * 2) 设置一个标识，用来判断先进入哪个锁中
 * 3）在第一个锁的同步代码块中，写第二把锁的同步代码块，使用synchronized可重入锁的性质，
 * 期间可以使用sleep睡几秒，使thread1不至于很快运行完成，没有出现2个线程锁互相请求的过程，看不到死锁的结果
 */
public class DeadLock implements Runnable {
    public String username;
    public Object lock1 = new Object();
    public Object lock2 = new Object();

    public void setFlag(String username) {
        this.username = username;
    }

    @Override
    public void run() {
        if ("a".equals(username)) {
            synchronized (lock1) {
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("按 lock1 => lock2 代码顺序执行了");
                }
            }
        }

        if ("b".equals(username)) {
            synchronized (lock2) {
                try {
                    System.out.println("username = " + username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("按 lock2 => lock1 代码顺序执行了");
                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {
        DeadLock t1 = new DeadLock();
        t1.setFlag("a");
        Thread thread1 = new Thread(t1);
        thread1.start();
        Thread.sleep(100);
        t1.setFlag("b");
        Thread thread2 = new Thread(t1);
        thread2.start();
    }
}
